package com.web.helper.calculation;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import io.github.coho04.githubapi.Github;
import io.github.coho04.githubapi.entities.GHUser;

import java.util.Arrays;
import java.util.List;

import static com.common.constant.Token.GITHUB_TOKEN;

/**
 * 计算 totalPullRequest,totalIssue,totalFork
 * return list
 * 未实现接口
 * 因为只能获得开发者最近260条的事件，数据逻辑上这个数值有问题
 */
public class CaculateEvents {

    public List<Integer> process(String username) {
        Github g = new Github(GITHUB_TOKEN);
        GHUser user = g.findUserByName(username);

        int totalPullRequest = 0;
        int totalFork = 0;
        int totalIssue = 0;

        //获取事件清单前缀
        String originalUrl = user.getReceivedEventsUrl();

        for(int curPage = 1;curPage <= 3; curPage++){
            //格式化url
            String formattedUrl = originalUrl + "?per_page=100&page=" + curPage;

            //获得最近用户
            String eventsResponse = HttpUtil.get(formattedUrl);

            // 检查是否获取到有效的响应
            if (eventsResponse == null || eventsResponse.trim().isEmpty()) {
                // 如果响应为空或仅包含空白字符，可以选择退出或继续循环
                break; // 或者进行其他处理
            }

            JSONArray eventsArray = null;

            try {
                // 尝试将响应解析为 JSONArray
                eventsArray = JSON.parseArray(eventsResponse);
            } catch (JSONException e) {
                //不符合格式则没有信息或遇到限制
                continue;
            }


            // 遍历每条事件记录
            for (int i = 0; i < eventsArray.size(); i++) {
                JSONObject eventObject = eventsArray.getJSONObject(i);

                String type = eventObject.getString("type");
                System.out.println("cur Event: " + type);
                switch (type){
                    case "ForkEvent":
                        totalFork++;
                        break;
                    case "IssuesEvent":
                        totalIssue++;
                        break;
                    case "IssueCommentEvent":
                        totalIssue++;
                        break;
                    case "PullRequestEvent":
                        totalPullRequest++;
                        break;
                    default:
                        break;
                }

            }

        }

        System.out.println("pr: " + totalPullRequest);
        System.out.println("issue: " + totalIssue);
        System.out.println("fork: " + totalFork);

        return Arrays.asList(totalPullRequest,totalIssue,totalFork);
    }
}
